import json
import re
import datetime
from html import escape

import requests

from config.config import config
from data.mysql_db import Post, DataManager
from utils import common


class BullStarClient:
    """
    公牛星球爬虫，用于爬取帖子入库，仅供学习与研究
    """

    def __init__(self, phone: str, password: str, forum_id: int):
        # 初始化接口
        self.forum_id = forum_id
        self.headers = {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
        }
        self.__login(phone, password)

    def __login(self, phone: str, password: str):
        """
        token 过期需要重新登陆
        :return:
        """

        # 创建会话对象
        session = requests.Session()
        login_data = {
            "login_type": "password",
            "phone": phone,
            "password": password
        }
        session.post("https://www.kdxingqiu.com/login/doLogin", data=login_data, headers=self.headers)
        response = session.get("https://www.kdxingqiu.com/refreshToken", headers=self.headers)

        data = response.json()
        if data.get("status") != "success":
            raise Exception(response.text)

        token_type = data["data"].get("token_type")
        access_token = data["data"].get("access_token")
        self.headers["Authorization"] = f"{token_type} {access_token}"

    def forum_list_latest(self, num: int):
        """
        获取最新的数据
        :return:
        """
        base_url = "https://api.kdxingqiu.com/v1/forum/forumListAll"
        params = {
            "forum_id": self.forum_id,
            "source": "pc",
            "num": num,
            "start_position": 0,
            "number": num,
            "request_method": "post"
        }

        # 发送 POST 请求
        response = requests.post(base_url, params=params, headers=self.headers)
        next_position, result = self.__parse_response(response)
        return result

    def __clean_html_tags(self, html_content):
        """使用正则表达式去除 HTML 标签"""
        return re.sub(r"<[^>]+>", "", html_content)

    def __parse_response(self, response):
        results = []
        data = response.json()
        if data.get("status") != "success":
            raise Exception(response.text)

        posts = data["data"].get("list", [])
        next_position = data["data"].get("next_start_position", None)

        if len(posts) == 0:
            return next_position, results

        for post in posts:
            content = post.get("content", "")
            if content is None or content == "":
                continue
            i = Post(post_id=post.get("id", 0),
                     forum_id=self.forum_id,
                     content=self.__clean_html_tags(content),
                     image=json.dumps(post.get("image")),
                     publish_time=post.get("create_at_time_stamp", ""))
            results.append(i)

        return next_position, results

    @staticmethod
    def pretty_html(post: Post):
        """
        将帖子内容渲染为 HTML 格式
        返回值为字符串，包含完整的 HTML 内容
        """
        # 渲染内容部分（使用 <p> 标签）
        content_html = f"<p>{escape(post.content)}</p>"
        create_time_html = f"<p>{post.publish_time}</p>"
        # 渲染图片部分（如果有）
        image_html = ""
        for img_url in post.image:
            image_html += f"<img src=\"{escape(img_url)}\" alt=\"图片\" style=\"max-width:100%; margin-top:10px;\" />\n"

        # 组合成完整的 HTML 布局
        html_output = f"<div class=\"post\">\n"
        html_output += f"  <div class=\"post-content\">\n"
        html_output += f"    {content_html}\n"
        html_output += f"    {image_html}"
        html_output += f"    {create_time_html}\n"
        html_output += f"  </div>\n"
        html_output += f"</div>"

        return html_output

    def crawl_forum_all(self, start_time: int, end_time: int) -> list:
        """
        爬取指定日期的全部数据
        :return:
        """
        base_url = "https://api.kdxingqiu.com/v1/forum/postsSearch"
        next_position = 0
        params = {
            "forum_id": self.forum_id,
            "source": "pc",
            "num": 7,
            "start_position": next_position,
            "number": 7,
            "request_method": "post",
            "start_time": start_time,
            "end_time": end_time,
        }
        results = []

        while True:
            if next_position is None:
                break
            params["start_position"] = next_position
            response = requests.post(base_url, params=params, headers=self.headers)
            next_position, result = self.__parse_response(response)
            results.extend(result)

            if len(result) == 0:
                break

        print(f"<UNK>: 共下载{len(results)}条评论")
        return results


if __name__ == '__main__':
    bull_star_config = config.get('bull_star', {})
    client = BullStarClient(bull_star_config.get("phone", ""),
                            bull_star_config.get("password", ""),
                            bull_star_config.get("forum_id", 0))
    #
    # start_dt = datetime.datetime(2025, 4, 30)
    # end_dt = datetime.datetime(2025, 6, 25)
    #
    # start_time = common.get_start_time_and_end_time(start_dt)[0]
    # end_time = common.get_start_time_and_end_time(end_dt)[1]

    start_time, end_time = common.get_start_time_and_end_time(datetime.datetime.now())
    resp = client.crawl_forum_all(start_time=start_time, end_time=end_time)
    manager = DataManager()
    manager.bulk_save_objects(resp)
